/**
 * Copyright (c)
 */

package com.qzsoft.system.modules.permission.user.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qzsoft.jeemis.common.annotation.LogOperation;
import com.qzsoft.jeemis.common.constant.Constant;
import com.qzsoft.jeemis.common.utils.ConvertUtils;
import com.qzsoft.jeemis.common.utils.ExcelUtils;
import com.qzsoft.jeemis.common.utils.Result;
import com.qzsoft.jeemis.common.validator.AssertUtils;
import com.qzsoft.jeemis.common.validator.ValidatorUtils;
import com.qzsoft.jeemis.common.validator.group.AddGroup;
import com.qzsoft.jeemis.common.validator.group.DefaultGroup;
import com.qzsoft.jeemis.common.validator.group.UpdateGroup;
import com.qzsoft.jeemis.platform.security.user.SecurityUser;
import com.qzsoft.jeemis.platform.user.dto.DeptAndUserDTO;
import com.qzsoft.system.common.PinYinUtils;
import com.qzsoft.system.modules.permission.role.service.SysRoleUserService;
import com.qzsoft.system.modules.permission.user.common.FileUtils;
import com.qzsoft.system.modules.permission.user.dto.PasswordDTO;
import com.qzsoft.system.modules.permission.user.dto.PinYinDto;
import com.qzsoft.system.modules.permission.user.dto.SysUserDTO;
import com.qzsoft.system.modules.permission.user.excel.SysUserExcel;
import com.qzsoft.system.modules.permission.user.service.SysUserService;
import com.qzsoft.system.repository.sys.entity.SysUserEntity;
import com.qzsoft.zhjd.common.utils.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 用户管理
 */
@RestController
@RequestMapping("/sys/user")
@Api(tags = "用户管理")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleUserService sysRoleUserService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "username", value = "用户名", paramType = "query", dataType = "String")
    })
    @RequiresPermissions("sys:user:page")
    public Result<IPage<SysUserEntity>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
        return new Result<IPage<SysUserEntity>>().ok(sysUserService.page(params));
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("sys:user:info")
    public Result<SysUserDTO> get(@PathVariable("id") Long id) {
        SysUserDTO data = sysUserService.get(id);

        //用户角色列表
        List<Long> roleIdList = sysRoleUserService.getRoleIdList(id);
        data.setRoleIdList(roleIdList);

        return new Result<SysUserDTO>().ok(data);
    }

    @GetMapping("info")
    @ApiOperation("登录用户信息")
    public Result<SysUserDTO> info() {
        /***************  2020-10-12 19:59:50  功能点检  高丙祥  MOD START  ***************/
        SysUserDTO data = ConvertUtils.sourceToTarget(SecurityUser.getUser(), SysUserDTO.class);
        SysUserDTO currentUserInfo = sysUserService.getCurrentUserInfo(SecurityUser.getUserId());
        return new Result<SysUserDTO>().ok(currentUserInfo);
        /***************  2020-10-12 19:59:50  功能点检  高丙祥  MOD END  ***************/
    }

    @PutMapping("password")
    @ApiOperation("修改密码")
    @LogOperation("修改密码")
    public Result password(@RequestBody PasswordDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto);

        sysUserService.updatePassword(dto);

        return new Result();
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("sys:user:save")
    public Result save(@RequestBody SysUserDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        sysUserService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("sys:user:update")
    public Result update(@RequestBody SysUserDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        sysUserService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("sys:user:delete")
    public Result delete(@RequestBody Long[] ids) {
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        sysUserService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("sys:user:export")
    @ApiImplicitParam(name = "username", value = "用户名", paramType = "query", dataType = "String")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<SysUserEntity> list = sysUserService.list(params);
        ExcelUtils.exportExcelToTarget(response, "导出用户列表", list, SysUserExcel.class);
    }

    @GetMapping("/list")
    public Result<List<SysUserEntity>>list (@RequestParam Map<String, Object> params) {
        List<SysUserEntity> list = sysUserService.list(params);
        return ResultUtils.ok(list);
    }
    //region 赵爱增加 去用户列表 实现前端选择用户 2020-8-28

    /**
     * 查询已选择的用户数据
     *
     * @param ids 用户ID，多个用逗号隔开
     * @return Result
     */
    @PostMapping("get_selected_user_list")
    @ApiOperation("信息")
    public Result<Map> getSelectedUserList(@RequestParam String ids) {
        List<Map<String, Object>> result = new ArrayList<>();
        if (StringUtils.isNotBlank(ids)) {
            List utList = Arrays.asList(ids.split(","));
            List<SysUserEntity> list = sysUserService.queryByUserIds(utList);
            for (SysUserEntity deptEntity : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("checked", true);
                map.put("count", 0);
                map.put("username", deptEntity.getUsername());
                map.put("realName", deptEntity.getRealName());
                map.put("name", deptEntity.getRealName());
                map.put("hasDept", false);
                map.put("deptInfo", deptEntity.getDeptName());
                map.put("headUrl", deptEntity.getHeadUrl());
                map.put("id", deptEntity.getUsername());
                result.add(map);
            }
        }
        return new Result().ok(result);
    }
    //endregion

    /***************  2020-10-10 15:25:50  代码迁移  高丙祥  ADD START  ***************/
    @GetMapping("pinyin")
    @ApiOperation("获取简拼和全拼")
    public Result getPinYin(@RequestParam String rawData) {
        PinYinDto pinYinDto = new PinYinDto();
        pinYinDto.setRawData(rawData);
        pinYinDto.setSpell(PinYinUtils.getSpell(rawData));
        pinYinDto.setFullPinYin(PinYinUtils.getFullPinYin(rawData));
        return new Result().ok(pinYinDto);
    }

    @PutMapping("/self")
    @ApiOperation("修改")
    @LogOperation("修改")
//	@RequiresPermissions("sys:user:update")
    public Result updateCurrentUserInfo(@RequestParam(required = false,name = "file") MultipartFile file, @RequestParam(name = "dto") String json){
        //效验数据
        JSONObject jsonObject = JSONObject.parseObject(json);
        SysUserDTO sysUserDTO = JSONObject.parseObject(json, SysUserDTO.class);
        ValidatorUtils.validateEntity(json, UpdateGroup.class, DefaultGroup.class);
        if (file != null) {
            MultipartFile []files =new MultipartFile[1];
            files[0] = file;
            String headUrl = FileUtils.saveFile(files);
            System.out.println("url:" + headUrl);
            sysUserDTO.setHeadUrl(headUrl);
        }

        sysUserService.updateCurrentUserInfo(sysUserDTO);

        return new Result();
    }
/***************  2020-10-10 15:50:50  代码迁移  高丙祥  ADD END  ***************/


// 李化军重写框架里面的用户部门获取方法

    @PostMapping({"dept_and_user"})
    @ApiOperation("取回机构和用户")
    public Result<List<DeptAndUserDTO>> getDeptAndUsers(String pid) {
        return (new Result()).ok(this.sysUserService.getDeptAndUsers(pid));
    }

    @PostMapping({"search_dept_and_user"})
    @ApiOperation("搜索机构和用户")
    public Result<List<DeptAndUserDTO>> getSearchDeptAndUser(String key) {
        return (new Result()).ok(this.sysUserService.getSearchDeptAndUser(key));
    }
}
